package com.qianwei.footpath.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class MemoryUtils {

    public static String getAvailableMemory() {
        long availableMemory = getAvailableMemoryInBytes();
        return formatMemory(availableMemory);
    }

    private static long getAvailableMemoryInBytes() {
        long availableMemory = 0;
        try (BufferedReader reader = new BufferedReader(new FileReader("/proc/meminfo"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("MemAvailable:")) {
                    availableMemory = parseMemInfo(line);
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return availableMemory;
    }

    private static long parseMemInfo(String memInfoLine) {
        String[] parts = memInfoLine.split("\\s+");
        return Long.parseLong(parts[1]) * 1024; // Convert from kB to bytes
    }

    private static String formatMemory(long bytes) {
        final long MB = 1024 * 1024; // 1 MB in bytes
        final long GB = 1024 * MB; // 1 GB in bytes

        if (bytes >= GB) {
            double memoryInGB = bytes / (double) GB;
            return String.format("%.2f GB", memoryInGB);
        } else {
            double memoryInMB = bytes / (double) MB;
            return String.format("%.2f MB", memoryInMB);
        }
    }
}

